package com.xbongbong.formula.qlexpress.operator.math;

import com.ql.util.express.Operator;
import com.ql.util.express.OperatorOfNumber;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;

/**
 * @author: wufeng
 * @date: 2018/7/9 19:59
 * @desrcption: 求算数平均数
 */
public class OperatorAverage extends Operator {



    public OperatorAverage(String name){
        this.name = name;
    }

    public OperatorAverage(String aAliasName, String aName, String errorInfo){
        this.aliasName = aAliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }

    @Override
    public Object executeInner(Object[] list) throws Exception {
        Object sum = 0;
        for(int i=0; i < list.length; i++){
            String string = list[i].toString();
            if (!RegexUtil.isNumber(string)) {
                throw new XbbException(ProErrorCodeEnum.API_ERROR_260017);
            }
            Object num = Double.valueOf(string);
            if (RegexUtil.isInteger(string)) {
                num = Long.valueOf(string);
            }
            sum =  OperatorOfNumber.add(sum, num, true);
        }

        Object result = Arith.div(((Number) sum).doubleValue(), list.length, Constant.SCALE);
        return result;

    }
}
